package com.ruoyi.web.api;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.ssh.JschUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.base.domain.*;
import com.ruoyi.base.domain.request.InventoryCache;
import com.ruoyi.base.domain.vo.GoodsInfo;
import com.ruoyi.base.domain.vo.PalletVO;
import com.ruoyi.base.domain.vo.ShelfPosition;
import com.ruoyi.base.service.*;
import com.ruoyi.common.bean.request.EPCPositionReques;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.config.GlobalConfig;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.websocket.WebSocketServer;
import com.ruoyi.framework.websocket.WebSocketUsers;
import com.ruoyi.system.domain.TbDevice;
import com.ruoyi.system.domain.TbEpcRecord;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.ITbDeviceService;
import com.ruoyi.system.service.ITbEpcRecordService;
import com.ruoyi.web.controller.base.BaseMatGroupController;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.parameters.P;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Size;
import javax.websocket.Session;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.web.controller.base.BaseMatGroupController.base64ToMultipartFile;

@RestController
@RequestMapping("/apiRfid")
public class ApiController extends BaseController {
    @Autowired
    private IBaseMatClassService baseMatClassService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IBaseMatService baseMatService;

    @Autowired
    private IBaseWarehouseService baseWarehouseService;

    @Autowired
    private IBaseMatGroupService baseMatGroupService;

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private IBaseMatBomService baseMatBomService;

    @Autowired
    private IBaseTrayMatService baseTrayMatService;

    @Autowired
    private IBaseLocationService baseLocationService;

    @Autowired
    private IBaseWorkshopService baseWorkshopService;


    @Autowired
    private IBaseSupplierService baseSupplierService;

    @Autowired
    private IBaseTaskService baseTaskService;

    @Autowired
    private IBaseTaskInfoService baseTaskInfoService;

    @Autowired
    private ITbEpcRecordService tbEpcRecordService;

    @Autowired
    private ITbDeviceService tbDeviceService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private IBaseTaskReviewerService baseTaskReviewerService;

    @Autowired
    private IUrgencyChangeRecordService urgencyChangeRecordService;


    /**
     * 查询货品分类
     */
    @GetMapping("/getBaseMatClass")
    public AjaxResult getBaseMatClass(BaseMatClass baseMatClass) {
        List<BaseMatClass> baseMatClasses = baseMatClassService.selectBaseMatClassList(baseMatClass);
        return AjaxResult.success(baseMatClasses);
    }

    /**
     * 查询所有货品和领导人
     */
    @GetMapping("/getAllBaseMatAndPerson")
    public AjaxResult getAllBaseMatAndPerson() {
        HashMap map = new HashMap();
        SysUser sysUser = new SysUser();
        List<BaseMat> list = baseMatService.list();
        List<SysUser> sysUsers = sysUserService.selectUserList(sysUser);
        map.put("baseMatList",list);
        map.put("personList",sysUsers);
        return AjaxResult.success(map);
    }

    /**
     * 查询仓库下拉框
     */
    @GetMapping("/getWarehouseList")
    public AjaxResult getWarehouseList(BaseWarehouse baseMatClass) {
        List<BaseWarehouse> baseWarehouses = baseWarehouseService.selectBaseWarehouseList(baseMatClass);
        return AjaxResult.success(baseWarehouses);
    }

    //标签打印
    @GetMapping("/getAllEpcListOption")
    public AjaxResult getAllEpcListOption() {
        HashMap map = new HashMap();
        //货架
        List<BaseWarehouse> baseWarehouses = baseWarehouseService.list();
        for (BaseWarehouse baseWarehouse:baseWarehouses ) {
            LambdaQueryWrapper<BaseLocation> groupLambdaQueryWrapper = new LambdaQueryWrapper<>();
            groupLambdaQueryWrapper.eq(BaseLocation::getWarehouseCode,baseWarehouse.getWarehouseCode());
            List<BaseLocation> list = baseLocationService.list(groupLambdaQueryWrapper);
            baseWarehouse.setLocationList(list);
        }

        //货位
        List<BaseLocation> locationList = baseLocationService.list();
        for (BaseLocation location:locationList ) {
            LambdaQueryWrapper<BaseWorkshop> groupLambdaQueryWrapper = new LambdaQueryWrapper<>();
            groupLambdaQueryWrapper.eq(BaseWorkshop::getLocationId,location.getLocationId());
            List<BaseWorkshop> list = baseWorkshopService.list(groupLambdaQueryWrapper);
            location.setBaseWorkshopList(list);
        }

        //叉车
        List<BaseSupplier> baseSuppliers = baseSupplierService.list();

        //托盘
        List<BaseMatBom> baseMatBoms = baseMatBomService.list();

        //货品
        List<BaseMatClass> baseMatClassList = baseMatClassService.list();
        for (BaseMatClass baseMatClass:baseMatClassList ) {
            LambdaQueryWrapper<BaseMat> groupLambdaQueryWrapper = new LambdaQueryWrapper<>();
            groupLambdaQueryWrapper.eq(BaseMat::getMatClass,baseMatClass.getClassCode());
            List<BaseMat> list = baseMatService.list(groupLambdaQueryWrapper);
            baseMatClass.setBaseMatList(list);
        }

        map.put("huopin",baseMatClassList);
        map.put("tuopan",baseMatBoms);
        map.put("chache",baseSuppliers);
        map.put("huowei",locationList);
        map.put("huojia",baseWarehouses);
        return AjaxResult.success(map);
    }

    /**
     * 新增分类
     */
    @PostMapping("/insertBaseMatClass")
    public AjaxResult insertBaseMatClass(@RequestBody BaseMatClass baseMatClass) {
        baseMatClassService.save(baseMatClass);
        return AjaxResult.success("新增分类成功");
    }

    /**
     * 新增货品
     */
    @PostMapping("/insertBaseMat")
    public AjaxResult insertBaseMat(@RequestBody BaseMat baseMat) {
        baseMatService.save(baseMat);
        return AjaxResult.success("新增分类成功");
    }

    /**
     * 新增出库任务
     */
    @PostMapping("/insertTask")
    public AjaxResult insertTask(@RequestBody BaseTask baseTask) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        baseTask.setCreateId(userId);
        SysUser sysUser = sysUserService.selectUserById(baseTask.getUserId());
         String nickName = sysUser.getNickName();

        if (baseTask.getIsUrgent()==0) {
            baseTask.setIsAuth(0);
        }else {
            baseTask.setIsAuth(1);
        }
        baseTask.setCreateTime(DateUtils.getNowDate());
        baseTaskService.save(baseTask);
        //添加任务详情
        List<BaseTaskInfo> baseTaskInfos = new ArrayList<>();
        if (baseTask.getIsUrgent()==0) {
            for (BaseMat baseMat:baseTask.getBaseMatList()) {
                BaseTaskInfo baseTaskInfo = new BaseTaskInfo();
                baseTaskInfo.setTargetType(0);
                baseTaskInfo.setCreateTime(DateUtils.getNowDate());
                baseTaskInfo.setTargetId(baseMat.getMatId());
                baseTaskInfo.setTarkId(baseTask.getId());
                baseTaskInfo.setNum(baseMat.getNum());
                baseTaskInfos.add(baseTaskInfo);
            }
        }else{//看起来像是所有的货品，但是已经废弃了
            List<BaseMat> list = baseMatService.list();
            for (BaseMat baseMat:list) {
                BaseTaskInfo baseTaskInfo = new BaseTaskInfo();
                baseTaskInfo.setCreateTime(DateUtils.getNowDate());
                baseTaskInfo.setTargetType(0);
                baseTaskInfo.setTargetId(baseMat.getMatId());
                baseTaskInfo.setTarkId(baseTask.getId());
                baseTaskInfo.setNum(baseMat.getSafetyStock());
                baseTaskInfos.add(baseTaskInfo);
            }
        }

        List<BaseTaskReviewer> reviewerList = new ArrayList<>();
        //添加审批人
        if(baseTask.getUserId()!=0){
            BaseTaskReviewer reviewer = new BaseTaskReviewer();
            reviewer.setStatus(0);
            reviewer.setLevel(1);
            reviewer.setUid(baseTask.getUserId());
            reviewer.setTaskId(baseTask.getId());
            reviewer.setIsShow(1);
            reviewerList.add(reviewer);
        }
        if(baseTask.getUserId1()!=0){
            BaseTaskReviewer reviewer = new BaseTaskReviewer();
            reviewer.setStatus(0);
            reviewer.setLevel(2);
            reviewer.setUid(baseTask.getUserId1());
            reviewer.setTaskId(baseTask.getId());
            reviewerList.add(reviewer);
        }
        if(baseTask.getUserId2()!=0){
            BaseTaskReviewer reviewer = new BaseTaskReviewer();
            reviewer.setStatus(0);
            reviewer.setLevel(3);
            reviewer.setUid(baseTask.getUserId2());
            reviewer.setTaskId(baseTask.getId());
            reviewerList.add(reviewer);
        }


        Boolean flag = transactionTemplate.execute(e->{
            baseTaskReviewerService.saveBatch(reviewerList);
            baseTaskInfoService.saveBatch(baseTaskInfos);
            return Boolean.TRUE;
        });

        if(!flag){
            throw new ServiceException("新增数据库数据出错");
        }

        return AjaxResult.success("新增出库任务");
    }

    /**
     * 已读我的任务
     */
    @GetMapping("/readMyTask")
    public TableDataInfo readMyTask(Integer status) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        HttpServletRequest request1 = ServletUtils.getRequest();
        String ip = IpUtils.getIpAddr(request1);
        BaseSupplier baseSupplier = baseSupplierService.getbyip(ip);
        if(ObjectUtil.isNull(baseSupplier))
            throw new ServiceException("非叉车终端");

        LambdaQueryWrapper<BaseTask> groupLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        groupLambdaQueryWrapper.eq(BaseTask::getCreateId,userId);
        groupLambdaQueryWrapper.eq(BaseTask::getIsRead,0);
        groupLambdaQueryWrapper.eq(BaseTask::getSupperId,baseSupplier.getSupplierId());

        List<BaseTask> baseTasks = baseTaskService.list(groupLambdaQueryWrapper).stream().map(i -> {
            i.setIsRead(1);
            return i;
        }).collect(Collectors.toList());
        baseTaskService.updateBatchById(baseTasks);


        startPage();
        LambdaQueryWrapper<BaseTask> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.eq(BaseTask::getIsAuth,1);
//        taskWrapper.eq(BaseTask::getCreateId,userId);
        taskWrapper.eq(BaseTask::getSupperId,baseSupplier.getSupplierId());
        taskWrapper.orderByDesc(BaseTask::getCreateTime);
        if(status==1){
            taskWrapper.in(BaseTask::getStatus, 1,3);
        }else{
            taskWrapper.eq(BaseTask::getStatus,status);
        }
//        taskWrapper.eq(BaseTask::getStatus,status);
        taskWrapper.orderByDesc(BaseTask::getCreateTime);
        List<BaseTask> list = baseTaskService.list(taskWrapper);
        if(CollectionUtils.isNotEmpty(list)){
            for(BaseTask task : list){
                SysUser sysUser = sysUserService.selectUserById(task.getUserId());
                task.setLeader(sysUser.getNickName());
                task.setLinkPhone(sysUser.getPhonenumber());

                LambdaQueryWrapper<BaseTaskInfo> baseTaskWrapper = new LambdaQueryWrapper<>();
                baseTaskWrapper.in(BaseTaskInfo::getTarkId,task.getId());
                List<BaseTaskInfo> collect = baseTaskInfoService.list(baseTaskWrapper).stream().map(i -> {
                    BaseMat byId = baseMatService.getById(i.getTargetId());
                    i.setBaseMat(byId);
                    return i;
                }).collect(Collectors.toList());
                task.setBaseTaskInfos(collect);
//                if (collect.size()>0) {
//                    LambdaQueryWrapper<BaseMat> baseMatLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                    baseMatLambdaQueryWrapper.in(BaseMat::getMatId,collect);
//                    List<BaseMat> list1 = baseMatService.list(baseMatLambdaQueryWrapper);
//                    task.setBaseMatList(list1);
//                }

//                mat.setMatGroupName(baseMatGroupService.selectBaseMatGroupNameByGroupCode(mat.getMatGroup()));
//                mat.setMatClassName(baseMatClassService.selectBaseMatClassNameByClassCode(mat.getMatClass()));
            }
        }
        return getDataTable(list);

    }

    /**
     * 我的任务是否未读
     */
    @GetMapping("/getMyTaskIsRead")
    public AjaxResult getMyTaskIsRead() {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        LambdaQueryWrapper<BaseTask> groupLambdaQueryWrapper = new LambdaQueryWrapper<>();
        groupLambdaQueryWrapper.eq(BaseTask::getCreateId,userId);
        groupLambdaQueryWrapper.eq(BaseTask::getIsRead,0);
        List<BaseTask> list = baseTaskService.list(groupLambdaQueryWrapper);
        if (list.size()>0) {
            return AjaxResult.success(0);
        }else {
            return AjaxResult.success(1);
        }
    }


    /**
     * 查看操作员日志
     */
    @GetMapping("/getOperatorLogs")
    public AjaxResult getOperatorLogs() {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        LambdaQueryWrapper<BaseTask> groupLambdaQueryWrapper = new LambdaQueryWrapper<>();
        groupLambdaQueryWrapper.eq(BaseTask::getCreateId,userId);
        groupLambdaQueryWrapper.eq(BaseTask::getIsRead,0);
        List<BaseTask> list = baseTaskService.list(groupLambdaQueryWrapper);
        if (list.size()>0) {
            return AjaxResult.success(0);
        }else {
            return AjaxResult.success(1);
        }

    }


    /**
     * 通行记录
     */
    @GetMapping("/getEpcRecordList")
    public AjaxResult getEpcRecordList() {
        List<TbEpcRecord> collect = tbEpcRecordService.list().stream().map(tbEpcRecord -> {
            TbDevice byId = tbDeviceService.getById(tbEpcRecord.getDeviceId());
            tbEpcRecord.setDeviceName(byId.getDeviceName());
            return tbEpcRecord;
        }).collect(Collectors.toList());
        return AjaxResult.success(collect);
    }

    /**
     * 审核任务
     */
    @GetMapping("/authTask")
    public AjaxResult getTaskListAll(BaseTask baseTask) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();

        if(baseTask.getIsAuth()==2){
            baseTaskService.updateById(baseTask);
            LambdaQueryWrapper<BaseTaskReviewer> lqw = new LambdaQueryWrapper<>();
            lqw.eq(BaseTaskReviewer::getTaskId,baseTask.getId());
            lqw.eq(BaseTaskReviewer::getUid,userId);
            BaseTaskReviewer baseTaskReviewer = baseTaskReviewerService.getOne(lqw);
            baseTaskReviewer.setRemark(baseTask.getRemark());
            baseTaskReviewer.setStatus(2);
            baseTaskReviewerService.updateById(baseTaskReviewer);
            return AjaxResult.success();
        }else if(baseTask.getIsAuth()==1){
            LambdaQueryWrapper<BaseTaskReviewer> lqw = new LambdaQueryWrapper<>();
            lqw.eq(BaseTaskReviewer::getUid,userId);
            lqw.eq(BaseTaskReviewer::getTaskId,baseTask.getId());
            BaseTaskReviewer baseTaskReviewer  = baseTaskReviewerService.getOne(lqw);
            baseTaskReviewer.setStatus(baseTask.getStatus());
            baseTaskReviewer.setRemark(baseTask.getRemark());
            baseTaskReviewerService.updateById(baseTaskReviewer);

            //修改下一个level的isShow
            lqw.clear();
            lqw.eq(BaseTaskReviewer::getTaskId,baseTask.getId());
            lqw.lt(BaseTaskReviewer::getStatus,3);
            Integer count = baseTaskReviewerService.count(lqw);
            if(count == baseTaskReviewer.getLevel()){
                baseTask.setIsAuth(1);
                baseTask.setStatus(1);
                //任务缓存
                List<Long> taskList = (List<Long>) redisTemplate.opsForValue().get("taskQueue");
                taskList.add(baseTask.getId());
                baseTaskService.updateById(baseTask);
                return AjaxResult.success();
            }else{
                lqw.clear();
                lqw.eq(BaseTaskReviewer::getTaskId,baseTask.getId());
                lqw.eq(BaseTaskReviewer::getLevel,baseTaskReviewer.getLevel()+1);
                BaseTaskReviewer baseTaskReviewer1 = baseTaskReviewerService.getOne(lqw);
                baseTaskReviewer1.setIsShow(1);
                baseTaskReviewerService.updateById(baseTaskReviewer1);
                return AjaxResult.success();
            }

        }else throw new ServiceException("传入参数非法");

    }

    /**
     * 更换审批人
     */
    @PostMapping("/changeReviewer")
    public AjaxResult changeReviewer(BaseTask request){
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        LambdaQueryWrapper<BaseTaskReviewer> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BaseTaskReviewer::getTaskId,request.getId());
        lqw.eq(BaseTaskReviewer::getUid,userId);
        BaseTaskReviewer originalReviewer = baseTaskReviewerService.getOne(lqw);
        if(ObjectUtil.isNull(originalReviewer))
            throw new ServiceException("非此项目审批人");

        originalReviewer.setStatus(3);
        baseTaskReviewerService.updateById(originalReviewer);

        BaseTaskReviewer reviewer = new BaseTaskReviewer();
        reviewer.setUid(request.getUserId());
        reviewer.setTaskId(request.getId());
        reviewer.setLevel(originalReviewer.getLevel());
        reviewer.setIsShow(1);
        baseTaskReviewerService.updateById(reviewer);
        return AjaxResult.success();
    }

    /**
     * 查询审核未审核记录
     */
    @GetMapping("/getTaskListAll")
    public TableDataInfo getTaskListAll(Integer isAuth) {

        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        LambdaQueryWrapper<BaseTaskReviewer> baseTaskReviewerlqw = new LambdaQueryWrapper<>();
        baseTaskReviewerlqw.eq(BaseTaskReviewer::getUid,userId);
        baseTaskReviewerlqw.eq(BaseTaskReviewer::getIsShow,1);
        if(isAuth==1){
            baseTaskReviewerlqw.ge(BaseTaskReviewer::getStatus,1);
        }else{
            baseTaskReviewerlqw.eq(BaseTaskReviewer::getStatus,0);
        }

        List<BaseTaskReviewer> taskList = baseTaskReviewerService.list(baseTaskReviewerlqw);
        if(taskList.isEmpty())
            throw new ServiceException("未查询到审批记录");


        startPage();
//        LambdaQueryWrapper<BaseTask> taskWrapper = new LambdaQueryWrapper<>();
//        taskWrapper.eq(BaseTask::getIsAuth,isAuth);
//        taskWrapper.orderByDesc(BaseTask::getCreateTime);
        List<BaseTask> list = taskList.stream().map(
                e->{
                    return baseTaskService.getById(e.getTaskId());
                }
        ).collect(Collectors.toList());


        if(CollectionUtils.isNotEmpty(list)){
            for(BaseTask task : list){
                SysUser sysUser = sysUserService.selectUserById(task.getUserId());
                task.setLeader(sysUser.getNickName());
                task.setLinkPhone(sysUser.getPhonenumber());

                LambdaQueryWrapper<BaseTaskInfo> baseTaskWrapper = new LambdaQueryWrapper<>();
                baseTaskWrapper.in(BaseTaskInfo::getTarkId,task.getId());
                List<BaseTaskInfo> collect = baseTaskInfoService.list(baseTaskWrapper).stream().map(i -> {
                    BaseMat byId = baseMatService.getById(i.getTargetId());
                    i.setBaseMat(byId);
                    return i;
                }).collect(Collectors.toList());
                task.setBaseTaskInfos(collect);
//                if (collect.size()>0) {
//                    LambdaQueryWrapper<BaseMat> baseMatLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                    baseMatLambdaQueryWrapper.in(BaseMat::getMatId,collect);
//                    List<BaseMat> list1 = baseMatService.list(baseMatLambdaQueryWrapper);
//                    task.setBaseMatList(list1);
//                }

//                mat.setMatGroupName(baseMatGroupService.selectBaseMatGroupNameByGroupCode(mat.getMatGroup()));
//                mat.setMatClassName(baseMatClassService.selectBaseMatClassNameByClassCode(mat.getMatClass()));
            }
        }
        return getDataTable(list);
    }
//
//    查询审批人信息
    @GetMapping("/getReviewer")
    public AjaxResult getReviewer(Integer taskId){
        LambdaQueryWrapper<BaseTaskReviewer> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BaseTaskReviewer::getTaskId,taskId);
        lqw.orderByAsc(BaseTaskReviewer::getLevel);
        List<BaseTaskReviewer> list = baseTaskReviewerService.list(lqw);
        list.forEach(item->{
            SysUser user = sysUserService.selectUserById(item.getUid());
            SysUser user1 = new SysUser();
            user1.setNickName(user.getNickName());
            user1.setRoles(user.getRoles());
            user1.setAvatar(user.getAvatar());
            item.setUser(user1);
        });
        return AjaxResult.success(list);
    }

    /**
     * 提交任务（打印rfid标签绑定货品）
     */
    @PostMapping("/insertTaskAndAmt")
    public AjaxResult insertTaskAndAmt(@RequestBody BaseMatGroup baseMatGroup) throws IOException, InterruptedException {
        baseMatGroup.setCreateBy(getUsername());

        //货品
        if (baseMatGroup.getTargetType()==0) {
            if (baseMatGroup.getTargetId()!=null) {
                BaseMat byId = baseMatService.getById(baseMatGroup.getTargetId());
                baseMatGroup.setPrefix("HP"+byId.getMatCode());
                baseMatGroup.setStatus(1);
            }

        }
        //叉车
        if (baseMatGroup.getTargetType()==1) {
            if (baseMatGroup.getTargetId()!=null) {
                BaseSupplier byId = baseSupplierService.getById(baseMatGroup.getTargetId());
                baseMatGroup.setPrefix("CC"+byId.getSupplierCode());
                baseMatGroup.setStatus(1);
            }

        }
        //托盘
        if (baseMatGroup.getTargetType()==2) {
            if (baseMatGroup.getTargetId()!=null) {
                BaseMatBom byId = baseMatBomService.getById(baseMatGroup.getTargetId());
                baseMatGroup.setPrefix("TP"+byId.getFatherMatCode());
                baseMatGroup.setStatus(1);
            }

        }
        //货位
        if (baseMatGroup.getTargetType()==3) {
            if (baseMatGroup.getTargetId()!=null) {
                BaseLocation byId = baseLocationService.getById(baseMatGroup.getTargetId());
                baseMatGroup.setPrefix("HW"+byId.getLocationCode());
                baseMatGroup.setStatus(1);
            }

        }

        //货架
        if (baseMatGroup.getTargetType()==4) {
            if (baseMatGroup.getTargetId()!=null) {
                BaseWarehouse byId = baseWarehouseService.getById(baseMatGroup.getTargetId());
                baseMatGroup.setPrefix("HJ"+byId.getWarehouseCode());
                baseMatGroup.setStatus(1);
            }

        }

        long count = baseMatGroupService.count(new LambdaQueryWrapper<BaseMatGroup>()
                .eq(BaseMatGroup::getPrefix, baseMatGroup.getPrefix()));
        List<BaseMatGroup> baseMatGroups = new ArrayList<>();
        for (Integer i=(int)count;i<baseMatGroup.getNumber()+count;i++) {
            BaseMatGroup carnum = new BaseMatGroup();
            carnum.setGroupNum(baseMatGroup.getPrefix()+BaseMatGroupController.addZeroForStr(i.toString(),16-baseMatGroup.getPrefix().length(),1));
            carnum.setPrefix(baseMatGroup.getPrefix());
            String qrCode = createQrCode(baseMatGroup.getPrefix() +BaseMatGroupController.addZeroForStr(i.toString(),16-baseMatGroup.getPrefix().length(),1), baseMatGroup.getPrefix());
            carnum.setQrCode(qrCode);
            carnum.setTargetType(baseMatGroup.getTargetType());
            carnum.setCreateBy(getUsername());
            carnum.setCreateTime(DateUtils.getNowDate());
            carnum.setTargetId(baseMatGroup.getTargetId());
            baseMatGroups.add(carnum);
//            tbCarnumService.save(carnum);
//            id.add(carnum.getId());
        }
        baseMatGroupService.saveBatch(baseMatGroups);
        BaseMatGroupController.dayin(baseMatGroups);
        return AjaxResult.success();
    }

    public  String createQrCode(String content,String name) throws IOException {
        String base64QRCode = QRCodeUtils.getBase64QRCode(content);
//            System.out.println(base64QRCode);
        //转换为二维码图片

        MultipartFile file = base64ToMultipartFile(base64QRCode);
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = serverConfig.getUrl() + fileName;


        return url.toString();
    }


    /**
     * 查询货品
     */
    @GetMapping("/getBaseMatList")
    public AjaxResult getBaseMatList(BaseMat baseMat) {
        List<BaseMat> list = baseMatService.selectBaseMatList(baseMat);
        return AjaxResult.success(list);
    }


    /**
     * 根据epc编码查询相关信息
     */
    @GetMapping("/getEpcNumToInfo")
    public AjaxResult getEpcNumToInfo(String epcNum) {
        LambdaQueryWrapper<BaseMatGroup> groupLambdaQueryWrapper = new LambdaQueryWrapper<>();
        groupLambdaQueryWrapper.eq(BaseMatGroup::getGroupNum,epcNum);
        BaseMatGroup one = baseMatGroupService.getOne(groupLambdaQueryWrapper);
        HashMap map = new HashMap();
        if (one!=null) {
            switch (one.getTargetType()){//判断标签
                case 0:
                    //货物
                    BaseMat goods = baseMatService.getById(one.getTargetId());
                    map.put("baseMat",goods);
                    break;
                case 4:
                    //货架
                    BaseLocation shelf = baseLocationService.getById(one.getTargetId());
                    //查该货架的货位
                    LambdaQueryWrapper<BaseWorkshop> lqw = new LambdaQueryWrapper<>();
                    lqw.eq(BaseWorkshop::getLocationId,shelf.getLocationId());
                    //TODO 差个判断是否空闲
//                    lqw.eq(BaseWorkshop::);
                    List<BaseWorkshop> tagertList = baseWorkshopService.list(lqw);
                    shelf.setWorkshopList(tagertList);
                    map.put("shelf",shelf);
                    break;
                case 2:
                    //托盘
                    BaseMatBom pallet = baseMatBomService.getById(one.getTargetId());
                    map.put("pallet",pallet);
                    break;
            }
        }
        if (map.isEmpty()) {
            return AjaxResult.error();
        }
        return AjaxResult.success(map);
    }


    /**
     * 绑定托盘(绑定货品) 记录单号//入库//记录谁开叉车账号的那个人记录任务id
     */
    @PostMapping("/bingBaseTrayMat")
    public AjaxResult bingBaseTrayMat(@RequestBody BaseMatGroup baseMatGroup) {

        //groupNum  托盘epc？
        LambdaQueryWrapper<BaseMatGroup> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(BaseMatGroup::getGroupNum,baseMatGroup.getGroupNum());
        BaseMatGroup one = baseMatGroupService.getOne(queryWrapper);

        //baseMatGroups 货品epc？
//        List<String> collect = baseMatGroup.getBaseMatGroups().stream().map(BaseMatGroup::getGroupNum).collect(Collectors.toList());
        List<String> collect = baseMatGroup.getHpepcList();
        LambdaQueryWrapper<BaseMatGroup> listQueryWrapper=new LambdaQueryWrapper<>();
        listQueryWrapper.in(BaseMatGroup::getGroupNum,collect);
        List<BaseMatGroup> list = baseMatGroupService.list(listQueryWrapper);


        //查托盘信息
        Long targetId = one.getTargetId();
        BaseMatBom byId = baseMatBomService.getById(targetId);
        if(ObjectUtil.isNull(one)){
            throw new ServiceException("查无此托盘");
        }

        //表处理
        List<BaseTrayMat> baseTrayMats = new ArrayList<>();
        for (BaseMatGroup matGroup:list){
            //查货
            Long targetId1 = matGroup.getTargetId();
            BaseMat byId1 = baseMatService.getById(targetId1);
            if(list.isEmpty())
                throw new ServiceException("货品数据为空或者查无此标签");

            Optional<BaseTrayMat> op =  baseTrayMats.stream()
                    .filter(a->a.getMatId()==byId1.getMatId())
                    .filter(a->a.getBomId()==byId.getBomId())
                    .findAny();

            //保存集合里有？
            if(!op.isPresent()){

                LambdaQueryWrapper<BaseTrayMat> lqw = new LambdaQueryWrapper<>();
                lqw.eq(BaseTrayMat::getMatId,byId1.getMatId());
                lqw.eq(BaseTrayMat::getBomId,byId.getBomId());
                lqw.eq(BaseTrayMat::getIsDel,0);
                BaseTrayMat baseTrayMat = baseTrayMatService.getOne(lqw);
                //数据库里面有？
                if(ObjectUtil.isNull(baseTrayMat)){
                    baseTrayMat = new BaseTrayMat();
                    baseTrayMat.setBomId(byId.getBomId());
                    baseTrayMat.setMatId(byId1.getMatId());
                    baseTrayMat.setNum(1);
                    baseTrayMats.add(baseTrayMat);
                }else {
                    baseTrayMat.setNum(baseTrayMat.getNum()+1);
                    baseTrayMats.add(baseTrayMat);
                }
            }else{
                BaseTrayMat baseTrayMat = op.get();
                baseTrayMat.setNum(baseTrayMat.getNum()+1);
            }

            matGroup.setBomId(byId.getBomId());
            baseMatGroupService.updateById(matGroup);
        }
        baseTrayMatService.saveOrUpdateBatch(baseTrayMats);
        return AjaxResult.success(byId);
    }


    /**
     * 查看分类（没有的话新增）
     */
    @PostMapping("/getBaseMatClass")
    public AjaxResult list(@RequestBody BaseMatClass baseMatClass) {
        List<BaseMatClass> baseMatClasses = baseMatClassService.selectBaseMatClassList(baseMatClass);
        return AjaxResult.success(baseMatClasses);
    }

    @PostMapping("/addInventoryCache")
    public AjaxResult addInventoryCache(@RequestBody InventoryCache request) {

        //TODO 记得补任务内容校验
        HttpServletRequest request1 = ServletUtils.getRequest();
        String ip = IpUtils.getIpAddr(request1);
        request.setIp(ip);
        BaseSupplier forkCar = baseSupplierService.getbyip(request.getIp());

        if(forkCar==null)
            return AjaxResult.error();

        //缓存+状态更新
        redisTemplate.opsForValue().set("forkcar-"+forkCar.getSupplierId()+"-task:"+request.getMissionId(),request);
        BaseTask task =  baseTaskService.getById(request.getMissionId());
        task.setStatus(3);
        baseTaskService.updateById(task);
        //发给大屏
        Session session = WebSocketUsers.get("dapin");
        if(ObjectUtil.isNotNull(session))
            WebSocketServer.sendMessageToUser(session,"{ \"type\":1,\"hasGoods\":true }");
        return AjaxResult.success(task);
//        return AjaxResult.succ.ess(baseMatClasses);
    }


    @PostMapping("/position")
    public AjaxResult position(@RequestBody EPCPositionReques reques) {
        LambdaQueryWrapper<BaseMatGroup> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BaseMatGroup::getGroupNum,reques.getEpc());
        BaseMatGroup baseMatGroup = baseMatGroupService.getOne(lqw);
        String position = new String();
        switch (baseMatGroup.getTargetType()){
            case 4:
                position = baseLocationService.getById(baseMatGroup.getTargetId()).getPosition();
                break;
        }
        Session session = WebSocketUsers.get("dapin");
        if(ObjectUtil.isNotNull(session))
            WebSocketServer.sendMessageToUser(session,"{\"type\":0,\"position\":"+position+"}");
        return AjaxResult.success("");
    }

    @GetMapping("initPosition")
    public AjaxResult initPosition(){
        //获取货架的位置信息
        List<BaseLocation> shelfList = baseLocationService.list();
        HashMap map = new HashMap<>();

        //拿货架位置
        List<ShelfPosition> list = shelfList.stream().map(item -> {
            ShelfPosition position = new ShelfPosition();
            // 创建 JSONObject
            JSONObject jsonObject = new JSONObject(item.getPosition());

            // 从 JSONObject 中获取各个字段的值
            int x = jsonObject.getInt("x");
            int y = jsonObject.getInt("y");
            int z = jsonObject.getInt("z");

            List<Integer> list1 = new ArrayList<>();
            list1.add(x);
            list1.add(y);
            list1.add(z);
            String s = list1.toString();

            position.setPosition(list1);

            HashMap map1 = new HashMap<>();
            map1.put("col",8);
            map1.put("layer",5);
            position.setLayout(map1);

            return position;
        }).collect(Collectors.toList());

        //拿货物位置
        LambdaQueryWrapper<BaseWorkshop> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(BaseWorkshop::getDelFlag,0);
        lqw1.eq(BaseWorkshop::getHasGoods,1);

        List<BaseWorkshop> cargoSpaceList = baseWorkshopService.list(lqw1);
        List<List<Integer>> goodsList = cargoSpaceList.stream().map(item ->{
            List<Integer> list1 = convertStringToList(item.getPosition());
            return list1;
        }).collect(Collectors.toList());

        map.put("shelfList",list);
        map.put("goodsList",goodsList);
        return AjaxResult.success(map);
    }


    @PostMapping("/storage")
    public AjaxResult storage(@RequestBody InventoryCache request){
        HttpServletRequest request1 = ServletUtils.getRequest();
        String ip = IpUtils.getIpAddr(request1);
        request.setIp(ip);
        BaseSupplier forkCar = baseSupplierService.getbyip(request.getIp());
        BaseWorkshop cargoSpace = request.getCargoSpace();


        if(forkCar==null)
            return AjaxResult.error();
        //缓存+状态更新
        InventoryCache cache = (InventoryCache)redisTemplate.opsForValue().get("forkcar-"+forkCar.getSupplierId()+"-task:"+request.getMissionId());
        BaseTask task = baseTaskService.getById(request.getMissionId());

        //托盘上货位
        BaseMatBom pallet =  cache.getPallet();
        pallet.setWorkshopId(cargoSpace.getWorkshopId());
        //任务的检测和修改
        //1.更新入库托盘
        LambdaQueryWrapper<BaseTaskInfo> taskInfolqw=  new LambdaQueryWrapper<>();
        taskInfolqw.eq(BaseTaskInfo::getTarkId,request.getMissionId());
        //这里并没有关于type的，TODO 现在只能以托盘位单位进行入库
        //taskInfolqw.eq(BaseTaskInfo::getTargetType,);
        taskInfolqw.eq(BaseTaskInfo::getTargetId,pallet.getBomId());
        BaseTaskInfo taskInfo = baseTaskInfoService.getOne(taskInfolqw);
        if(ObjectUtil.isNull(taskInfo))
            throw new ServiceException("任务详情数据不匹配");
        taskInfo.setStatus(1);
        try{
            baseTaskInfoService.updateById(taskInfo);
        }catch (Exception e){
            return AjaxResult.error();
        }
        //2.查询任务剩余没有入库的托盘
        taskInfolqw.clear();
        taskInfolqw.eq(BaseTaskInfo::getTarkId,cache.getMissionId());
        taskInfolqw.eq(BaseTaskInfo::getStatus,0);
        List<BaseTaskInfo> freeList = baseTaskInfoService.list(taskInfolqw);
        Integer taskSchedule = freeList.size();
        //3.处理任务状态并返回
        if(taskSchedule.equals(0)){
            task.setStatus(2);
        }else {
            task.setStatus(1);
        }
        //计算货物位置   ?你在计算nm呢，直接拿数据
//        BaseLocation shelf = baseLocationService.getById(cargoSpace.getLocationId());
//        if(ObjectUtil.isNull(shelf))
//            return AjaxResult.error();
//        JSONObject jsonObject = new JSONObject(shelf.getPosition());
//        Integer x = jsonObject.getInt("x");
//        Integer y = jsonObject.getInt("y")+Integer.parseInt(cargoSpace.getPliesNum())*73;
//        Integer z = jsonObject.getInt("z");
//        List<Integer> list1 = new ArrayList<>();
//        list1.add(x);
//        list1.add(y);
//        list1.add(z);
//        cargoSpace.setPosition(list1.toString());
        List<Integer> list1 = convertStringToList(cargoSpace.getPosition());

        cargoSpace.setHasGoods(1);


        Boolean flag = transactionTemplate.execute(e->{
            try {
                baseMatBomService.updateById(pallet);
                baseWorkshopService.updateById(cargoSpace);
                baseTaskService.updateById(task);
                return Boolean.TRUE;
            }catch (Exception ex){
                return Boolean.FALSE;
            }
        });

        if(!flag)
            return AjaxResult.error();
        task.setFreeList(freeList.stream().map(
               e->{
                   BaseMatBom pallet1 = baseMatBomService.getById(e.getTargetId());
                   return pallet1;
               }
        ).collect(Collectors.toList()));
        //反馈给大屏
        Session session = WebSocketUsers.get("dapin");
        if(ObjectUtil.isNotNull(session))
            WebSocketServer.sendMessageToUser(session,"{\"type\":2,\"position\":"+list1+"}");
        return AjaxResult.success(task);
    }

    public static List<Integer> convertStringToList(String str) {
        List<Integer> result = new ArrayList<>();

        // 去除方括号并去除空格
        str = str.replace("[", "").replace("]", "").trim();

        // 分割字符串
        String[] parts = str.split(",");

        try {
            for (String part : parts) {
                result.add(Integer.parseInt(part.trim()));
            }
        } catch (NumberFormatException e) {
            System.out.println("转换失败：" + e.getMessage());
        }

        return result;
    }

    @GetMapping("/getGoodsByPallet")
    public AjaxResult getGoodsByPallet(Long palletId){
        HashMap map = new HashMap<>();
        List <BaseTrayMat> palletList = baseTrayMatService.getByBomId(palletId);
        List<GoodsInfo> list = palletList.stream().map(
                item->{
                    BaseMat good = baseMatService.getById(item.getMatId());
                    GoodsInfo goodsInfo = new GoodsInfo();
                    goodsInfo.setName(good.getMatName());
                    goodsInfo.setNum(item.getNum());
                    return goodsInfo;
                }
        ).collect(Collectors.toList());
        return AjaxResult.success(list);
    }

    //获取未入库的托盘list和需要出库的货品List
    @GetMapping("/getTaskInfo")
    public AjaxResult getTaskInfo(Long taskId){
        BaseTask task = baseTaskService.getById(taskId);
        LambdaQueryWrapper<BaseTaskInfo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BaseTaskInfo::getTarkId,taskId);
        lqw.eq(BaseTaskInfo::getStatus,0);

        if (task.getTarkType().equals(0)){
            List<BaseMatBom> responseList = baseTaskInfoService.list(lqw).stream().map(e->{
                BaseMatBom pallet = baseMatBomService.getById(e.getTargetId());
                return pallet;
            }).collect(Collectors.toList());
            return AjaxResult.success(responseList);
        }else {
            List<GoodsInfo> responseList =baseTaskInfoService.list(lqw).stream().map(e->{
                GoodsInfo goodsInfo = new GoodsInfo();
                BaseMat baseMat = baseMatService.getById(e.getTargetId());
                goodsInfo.setName(baseMat.getMatName());
                goodsInfo.setId(baseMat.getMatId());
                goodsInfo.setNum(e.getNum().intValue());
                goodsInfo.setSchedule(e.getSchedule());
                return goodsInfo;
            }).collect(Collectors.toList());
            return AjaxResult.success(responseList);
        }
    }

    @PostMapping("/exWarehouse")
    public AjaxResult exWarehouse(@RequestBody InventoryCache request){

        HttpServletRequest request1 = ServletUtils.getRequest();
        String ip = IpUtils.getIpAddr(request1);

        BaseSupplier forkCar = baseSupplierService.getbyip(ip);
        BaseWorkshop cargoSpace = request.getCargoSpace();
        BaseTask task = baseTaskService.getById(request.getMissionId());

        //货架下架货物
        cargoSpace.setHasGoods(0);
        //缓存叉车跟托盘
        LambdaQueryWrapper<BaseMatBom> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BaseMatBom::getWorkshopId,cargoSpace.getWorkshopId());
        BaseMatBom pallet = baseMatBomService.getOne(lqw);
        request.setPallet(pallet);
        redisTemplate.opsForValue().set("forkcar-"+forkCar.getSupplierId()+"-task:"+request.getMissionId(),request);

        Boolean flag = transactionTemplate.execute(e->{
            baseWorkshopService.updateById(cargoSpace);
            task.setStatus(3);
            baseTaskService.updateById(task);
            return Boolean.TRUE;
        });

        if(!flag)
            return AjaxResult.error("更新数据库出错");
//
        //反馈给大屏
        List<Integer> list1 = convertStringToList(cargoSpace.getPosition());
        Session session = WebSocketUsers.get("dapin");
        if(ObjectUtil.isNotNull(session))
            WebSocketServer.sendMessageToUser(session,"{\"type\":3,\"position\":"+list1+",\"hasGoods\":true }");

        return AjaxResult.success(task);
    }


    @PostMapping("/recordTheOutedGoods")
    public AjaxResult recordTheOutedGoods(@RequestBody InventoryCache request){
        HttpServletRequest request1 = ServletUtils.getRequest();
        String ip = IpUtils.getIpAddr(request1);
        request.setIp(ip);
        BaseSupplier forkCar = baseSupplierService.getbyip(request.getIp());
        InventoryCache cache = (InventoryCache)redisTemplate.opsForValue().get("forkcar-"+forkCar.getSupplierId()+"-task:"+request.getMissionId());
        List<GoodsInfo> goodsInfoList = new ArrayList<>();
        List<BaseMatGroup> baseMatGroupList = new ArrayList<>();
        List<BaseTaskInfo> baseTaskInfoList = new ArrayList<>();
        List<BaseTrayMat> toUpdateBaseTrayMats = new ArrayList<>();
        //修改epc标签信息为已出库
        request.getEpcList().forEach(e->{
            LambdaQueryWrapper<BaseMatGroup> lqw  = new LambdaQueryWrapper<>();
            lqw.eq(BaseMatGroup::getGroupNum,e);
            lqw.le(BaseMatGroup::getStatus,3);
            BaseMatGroup baseMatGroup = baseMatGroupService.getOne(lqw);
             if(ObjectUtil.isNull(baseMatGroup))
                throw new ServiceException("epc数据非法，标签可能已出库或不存在");
            baseMatGroup.setStatus(3);
                baseMatGroupList.add(baseMatGroup);
            //分组统计出库货品数量
            Optional<GoodsInfo> optionalItem = goodsInfoList.stream().filter(item -> Objects.equals(item.getId(), baseMatGroup.getTargetId())).findFirst();
            if (optionalItem.isPresent()) {
                // 找到匹配项，更新其num值
                GoodsInfo item = optionalItem.get();
                item.setNum(item.getNum()+1);
            } else {
                // 未找到匹配项，新增项
                GoodsInfo goodsInfo = new GoodsInfo();
                goodsInfo.setNum(1);
                goodsInfo.setId(baseMatGroup.getTargetId());
                goodsInfoList.add(goodsInfo);
            }
//            if(ObjectUtil.isNull(goodsInfo)){
//                GoodsInfo newgoodsInfo = new GoodsInfo();
//                newgoodsInfo.setId(baseMatGroup.getTargetId());
//                newgoodsInfo.setNum(1);
//                goodsInfoList.add(newgoodsInfo);
//            }else{
//                goodsInfo.setNum(goodsInfo.getNum()+1);
//            }

        });

        //检测任务进度
        //1.1查任务
        BaseTask task = baseTaskService.getById(request.getMissionId());
        if(ObjectUtil.isNull(task)){
            return AjaxResult.error("查询任务信息出错");
        }

        //1.2出库数量对比
        goodsInfoList.forEach(item->{
            LambdaQueryWrapper<BaseTaskInfo> lqw = new LambdaQueryWrapper<>();
            lqw.eq(BaseTaskInfo::getTarkId,task.getId());
            lqw.eq(BaseTaskInfo::getTargetId,item.getId());
            BaseTaskInfo baseTaskInfo = baseTaskInfoService.getOne(lqw);

            if(ObjectUtil.isNull(baseTaskInfo))
                throw new ServiceException("检测到出库任务以外的货物");

            LambdaQueryWrapper<BaseTrayMat> baseTrayMatLQW = new LambdaQueryWrapper<>();
            baseTrayMatLQW.eq(BaseTrayMat::getBomId,cache.getPallet().getBomId());
            baseTrayMatLQW.eq(BaseTrayMat::getMatId,item.getId());
            baseTrayMatLQW.eq(BaseTrayMat::getIsDel,0);
            BaseTrayMat baseTrayMat = baseTrayMatService.getOne(baseTrayMatLQW);
            if(ObjectUtil.isNull(baseTrayMat))
                throw new ServiceException("检测到不属于托盘的货品");
            if(baseTrayMat.getNum()<item.getNum())
                throw new ServiceException("货品数量非法");
            baseTrayMat.setNum(baseTrayMat.getNum()-item.getNum());
            if(baseTrayMat.getNum().equals(0))
                baseTrayMat.setIsDel(1);
            toUpdateBaseTrayMats.add(baseTrayMat);

            Long newCount = baseTaskInfo.getSchedule()+item.getNum();
            if(newCount.equals(baseTaskInfo.getNum())){
                baseTaskInfo.setSchedule(newCount);
                baseTaskInfo.setStatus(1);
                baseTaskInfoList.add(baseTaskInfo);
            }else if(newCount<baseTaskInfo.getNum()){
                baseTaskInfo.setSchedule(newCount);
                baseTaskInfoList.add(baseTaskInfo);
            }else if(newCount>baseTaskInfo.getNum()){
                throw new ServiceException("货物数量超出限额，请检查");
            }



        });

        //数据库操作
        Boolean flag = transactionTemplate.execute(e->{
            baseTaskInfoList.forEach(item->{
                baseTaskInfoService.updateById(item);
            });

            //查询是否剩余出库需求
            LambdaQueryWrapper<BaseTaskInfo> lqw = new LambdaQueryWrapper<>();
            lqw.eq(BaseTaskInfo::getTarkId,task.getId());
            lqw.eq(BaseTaskInfo::getStatus,0);
            Integer taskSchedule = baseTaskInfoService.count(lqw);
            if(taskSchedule.equals(0)) {
                task.setStatus(2);
                baseTaskService.updateById(task);
            };

            baseMatGroupList.forEach(item->{
                baseMatGroupService.updateById(item);
            });

            toUpdateBaseTrayMats.forEach(item->{
                baseTrayMatService.updateById(item);
            });
            return Boolean.TRUE;
        });


        //2.查托盘是否剩余
        long count = toUpdateBaseTrayMats.stream()
                .filter(item -> item.getIsDel().equals(1))
                .count();



        HashMap map = new HashMap<>();
        map.put("task",task);
        map.put("count",count);
        return AjaxResult.success(map);
    }


    @PostMapping("/updatePallet")
    public AjaxResult updatePallet(PalletVO pallet){
        if(pallet.getPalletId()==-1)
            throw new ServiceException("缺少托盘参数");
        BaseMatBom res = baseMatBomService.getById(pallet.getPalletId());
        switch (pallet.getType()){
            case 1:
                if(pallet.getStatus().equals(-1))
                    throw new ServiceException("参数传递错误");
                res.setWorkshopId(null);
                break;
            case 2:
                if(pallet.getWorkshopId()==-1)
                    throw new ServiceException("参数传递错误");
                res.setWorkshopId(pallet.getWorkshopId());
                BaseWorkshop cargoSpace = baseWorkshopService.getById(pallet.getWorkshopId());
                if(ObjectUtil.isNull(cargoSpace))
                    throw new ServiceException("货位信息查询失败");
                cargoSpace.setHasGoods(1);
                baseWorkshopService.updateById(cargoSpace);
                break;
        }
        baseMatBomService.updateById(res);
        return AjaxResult.success();
    }

    //创建入库任务
    @PostMapping("/createInTask")
    public AjaxResult createInTask(@RequestBody InventoryCache cache){
        List<BaseMatBom> request = cache.getPalletList();
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
//        List<Long> list = (List<Long>) redisTemplate.opsForValue().get("onlineForkliftQueue");
//        if(list==null)
//            throw new ServiceException("错我");
//        Random random = new Random();
//        int index = random.nextInt(list.size());
//        Long supplierId = list.get(index);

        BaseTask baseTask = new BaseTask();
        baseTask.setCreateId(userId);
        baseTask.setTarkName("入库任务");
        baseTask.setIsAuth(1);
        baseTask.setIsUrgent(0);
        baseTask.setUserId(userId);
        baseTask.setStatus(1);
//        baseTask.setSupperId(supplierId);
        baseTaskService.save(baseTask);

        List<Long> list =  (List<Long>)redisTemplate.opsForValue().get("taskQueue");
        list.add(baseTask.getId());
        List<BaseTaskInfo> baseTaskInfos = new ArrayList<>();
        request.forEach(item->{
            BaseTaskInfo baseTaskInfo = new BaseTaskInfo();
            baseTaskInfo.setTarkId(baseTask.getId());
            baseTaskInfo.setTargetType(2);
            baseTaskInfo.setTargetId(item.getBomId());
            baseTaskInfo.setNum(1L);
            baseTaskInfo.setStatus(0);
            baseTaskInfo.setAccess(0);
            baseTaskInfos.add(baseTaskInfo);
        });
        baseTaskInfoService.saveBatch(baseTaskInfos);
        return AjaxResult.success("新增入库任务");
    }

    @GetMapping("/changeUrgency")
    public AjaxResult changeUrgency(){
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        UrgencyChangeRecord urgencyChangeRecord = new UrgencyChangeRecord();
        urgencyChangeRecord.setUid(userId);
        if(GlobalConfig.urgencyStatus==0){
            GlobalConfig.urgencyStatus=1;
            urgencyChangeRecord.setStatus(1);
        }else{
            GlobalConfig.urgencyStatus=0;
            urgencyChangeRecord.setStatus(0);
        }
        urgencyChangeRecordService.save(urgencyChangeRecord);
        return AjaxResult.success();
    }

    @GetMapping("/getUrgencyStatus")
    public AjaxResult getUrgencyStatus(){
        return AjaxResult.success(GlobalConfig.urgencyStatus==1);
    }
}
